<!--设备管理-->
<template>
    <div class="mainDesc">
        <div class="returnUpBack"><a @click="returnUp"><span>返回用户列表</span><em class="iconfont back"></em></a></div>
        <div class="descLeft">
            <div class="descTit">角色信息</div>
            <p>角色名称：<span>{{roleName}}</span></p>
            <p v-if="perms.sysOrg">机构名称：<span>{{orgName}}</span></p>
        </div>
        <div class="descRight">
            <a-tabs defaultActiveKey="1" @change="changeTab">
                <a-tab-pane v-if="perms.loadRoleResources" tab="角色资源"  name="1" id="1" key="1">
                    <div style="height:580px;overflow: auto; background: #f7f8fb; margin-top:16px; width: 80%">
                        <a-row style="margin-left: 5%">
                            <a-tree
                                    checkable
                                    :autoExpandParent="autoExpandParent" @expand="onExpand"
                                    :checkedKeys="checkedKeys" :expandedKeys="expandedKeys"
                                    :treeData='roleResTreeList'  @check="this.onCheck"></a-tree>
                        </a-row>
                    </div>
                    <a-row style="margin-top:26px; width: 80%">
                        <a-button type="default" @click="copyRoleResource" v-if="perms.saveOrUpdRoleResources" style="float: left">
                            从角色复制
                        </a-button>
                        <a-button type="primary" @click="saveTree" v-if="perms.saveOrUpdRoleResources" style="float: right">保存
                        </a-button>
                        <a-button type="default" @click="resetTree"
                                  v-if="perms.saveOrUpdRoleResources"  style="float: right; margin-right: 20px">重置
                        </a-button>
                    </a-row>
                </a-tab-pane>
                <a-tab-pane tab="角色菜单管理"  name="3" id="3" key="3">
                    <div style="height:580px;overflow: auto; background: #f7f8fb; margin-top:16px; width: 80%">
                        <a-row style="margin-left: 5%">
                            <a-tree
                                    checkable
                                    :autoExpandParent="autoMenuExpandParent" @expand="onmEenuExpand"
                                    :checkedKeys="checkedMenuKeys" :expandedKeys="expandedMenuKeys"
                                    :treeData='menuAllList'  @check="this.onEenuCheck"></a-tree>
                        </a-row>
                    </div>
                    <a-row style="margin-top:26px; width: 80%">
                        <a-button type="primary" @click="saveMenuTree" style="float: right">保存
                        </a-button>
                    </a-row>
                </a-tab-pane>
                <a-tab-pane v-if="perms.findRoleUsers" tab="角色用户管理"  name="2" id="2" key="2">
                    <div style=" margin-top:16px;">
                        <a-transfer
                                showSearch
                                :dataSource="totalUsers"
                                :targetKeys="userKeys"
                                :render="item=>item.label + ' - ' + item.description"
                                @change="handleChange" :titles='titles' filterable :filterMethod="filterMethod"
                                :listStyle="{'height':'610px',width:'45%'}"></a-transfer>
                    </div>
                </a-tab-pane>
            </a-tabs>
        </div>
        <copy-role ref="copyRole" :currentRoleId="roleId" @loadCopyRoleRes="loadCopyRoleRes" />
    </div>
</template>

<script>
    import { mapState } from 'vuex'
    import copyRole from './copyRole.vue'
    import Util from '@/libs/util';

    export default {
        name: 'device_list',
        components: {
            copyRole
        },
        data () {
            return {
                title: true,
                currentTabName: '1',
                perms: {},
                roleId: '',
                roleName: '',
                orgName: '',
                array: [ 10, 20, 30, 40 ],
                roleResTreeList: [],
                totalUsers: [],
                userKeys: [],
                titles: [ '未分配用户', '已分配用户' ],
                columns2: [
                    {
                        type: 'index',
                        title: '序号',
                        align: 'center',
                        width: 70
                    },
                    {
                        key: 'name',
                        title: '姓名',
                        align: 'center'
                    },
                    {
                        key: 'sfzjh',
                        title: '身份证件号',
                        align: 'center'
                    },
                    {
                        key: 'validStatus',
                        title: '启用状态',
                        align: 'center',
                        render: ( h, params ) => {
                            const row = params.row
                            return h ('span', {}, stateFilter (row.validStatus, 'enableStatus'))
                        }
                    },
                    {
                        key: 'createTime',
                        title: '创建时间',
                        align: 'center'
                    }
                ],
                autoExpandParent:true,
                checkedKeys:[],
                expandedKeys: [],
                menuAllList:[],
                checkedMenuKeys:[],
                expandedMenuKeys:[],
                autoMenuExpandParent:true,
            }
        },
        computed: {
            gesRoleUserList () {
                return this.$store.state.sysRole.sysRoleUser.sysRoleUserDTOS
            },
            ...mapState ({
                pageVal: state => state.sysRole.sysRoleUser.page
            }),
            queryPara () {
                return this.$store.state.sysRole.queryPara
            }
        },
        methods: {
            onExpand (expandedKeys) {
                this.expandedKeys = expandedKeys
                this.autoExpandParent = false
            },
            onmEenuExpand (expandedKeys) {
                this.expandedMenuKeys = expandedKeys
                this.autoMenuExpandParent = false
            },
            onEenuCheck (checkedKeys, info) {
                this.checkedMenuKeys = checkedKeys
            },
            onSelect (selectedKeys, info) {

            },
            onCheck (checkedKeys, info) {
                this.checkedKeys = checkedKeys
            },
            /**
             * Function    : initPermission
             * Description : 初始化权限码
             * Input       : none
             * Return      : none
             */
            initPermission () {
                this.perms = {
                    loadRoleResources: this.hasPermission ('sysrole:loadRoleResources'),
                    saveOrUpdRoleResources: this.hasPermission ('sysrole:saveOrUpdRoleResources'),
                    findRoleUsers: this.hasPermission ('sysrole:findRoleUsers'),
                    addRoleUsers: this.hasPermission ('sysrole:addRoleUsers'),
                    delRoleUsers: this.hasPermission ('sysrole:delRoleUsers')
                }
            },

            /**
             * Function    : initQueryParms
             * Description : 初始化$route.query参数
             * Input       : searchKey,departmentId
             * Return      : list
             */
            initQueryParms () {
                this.roleId = this.$route.query.id.toString ()
                this.roleName = this.$route.query.name.toString ()
                this.orgName = this.$route.query.orgName.toString ()
            },

            /**
             * Function    : init
             * Description : 初始化列表
             * Input       : searchKey,departmentId
             * Return      : list
             */
            init () {
                let para = Object.assign ({}, {roleId: this.roleId})
                if (this.currentTabName === '1') {
                    this.$store.dispatch ('loadSysRoleResAct', para).then (data => {
                        this.roleResTreeList = data
                        this.checkedKeys = Util.setTreeChecked(this.roleResTreeList,[])
                        this.expandedKeys = Util.expandedKeysAll(data,[])
                    })
                }else if (this.currentTabName === '3') {
                    let _this = this
                    _this.$get('sysrole/loadRoleMenu', para).then (data => {
                        _this.menuAllList = data
                        _this.checkedMenuKeys = Util.setTreeChecked(this.menuAllList,[])
                        _this.expandedMenuKeys = Util.expandedKeysAll(data,[])
                    })
                   /* this.$store.dispatch ('loadSysRoleResAct', para).then (data => {
                        this.menuAllList = data
                        this.checkedMenuKeys = Util.setTreeChecked(this.menuAllList,[])
                        this.expandedMenuKeys = Util.expandedKeysAll(data,[])
                    })*/
                }  else {
                    this.$store.dispatch ('findRoleUsersAct', para).then (res => {
                        this.totalUsers = res.data
                        this.totalUsers.forEach (item => {
                            item.title = item.label
                        })
                        this.userKeys = res.targetKeys
                    })
                }
            },
            saveMenuTree () {
                let _this = this
                let checkedNodes = this.getCheckedNodes ()
                let menuIds = this.checkedMenuKeys.join(',')
                /*this.$store.dispatch ('saveOrUpdRoleResourcesAct', {roleId: this.roleId, resIds}).then (res => {
                    if (res.code === 0) {
                        this.$message.success (res.message)
                        this.init ()
                    } else {
                        this.$message.error (res.message)
                    }
                })*/
                _this.$post ('sysrole/saveOrUpdRoleMenu', {roleId: this.roleId, menuIds}).then (res => {
                    if (res.code === 0) {
                        this.$message.success (res.message)
                        this.init ()
                    } else {
                        this.$message.error (res.message)
                    }
                })
            },

            /**
             * Function    : returnUp
             * Description : 页面返回上一级
             * Input       : none
             * Return      : none
             */
            returnUp () {
                this.$router.push ({
                    name: 'sysRole',
                    query: this.queryPara
                })
            },

            /**
             * Function    : changeTab
             * Description : 切换tab页面
             * Input       : name  tab中指定名称
             * Return      : none
             */
            changeTab ( name ) {
                this.currentTabName = name
                this.init ()
            },

            /**
             * Function    : changePage
             * Description : 切换页码
             * Input       : val
             * Return      : none
             */
            changePage ( val ) {
                this.page.currentPage = val
                this.init ()
            },

            /**
             * Function    : changePageSize
             * Description : 切换每页条数
             * Input       : vm
             * Return      : none
             */
            changePageSize ( vm ) {
                this.page.pageSize = vm
                this.page.currentPage = 1
                this.init ()
            },
            getSelectedNodes () {
                return this.roleResTreeList.filter(obj => obj.node.selected).map(obj => obj.node);
            },
            getCheckedNodes () {
                /* public API */
               /* return this.roleResTreeList.filter(obj => obj.node.checked).map(obj => obj.node);*/
                return this.roleResTreeList.filter(function (obj) {
                    return obj.checked;
                });
            },

            /**
             * Function    : saveTree
             * Description : 保存资源树
             * Input       : none
             * Return      : none
             */
            saveTree () {
                let checkedNodes = this.getCheckedNodes ()
                let resIds = this.checkedKeys.join(',')
                this.$store.dispatch ('saveOrUpdRoleResourcesAct', {roleId: this.roleId, resIds}).then (res => {
                    if (res.code === 0) {
                        this.$message.success (res.message)
                        this.init ()
                    } else {
                        this.$message.error (res.message)
                    }
                })
            },

            /**
             * Function    : resetTree
             * Description : 重置树
             * Input       : none
             * Return      : none
             */
            resetTree () {
                this.init ()
            },

            /**
             * Function    : renderUser
             * Description : 渲染树
             * Input       : item
             * Return      : none
             */
            renderUser ( item ) {
                return item.label + ' - ' + item.description
            },

            /**
             * Function    : filterMethod
             * Description : 用户信息过滤
             * Input       : data query
             * Return      : none
             */
            filterMethod ( data, query ) {
                return data.label.indexOf (query) > -1 || data.description.indexOf (query) > -1
            },

            /**
             * Function    : copyRoleResource
             * Description : 打开遮罩页
             * Input       : none
             * Return      : none
             */
            copyRoleResource () {
                this.$refs[ 'copyRole' ].showModal ()
            },

            /**
             * Function    : loadCopyRoleRes
             * Description : 加载复制的角色资源
             * Input       : roleId - 被选中的角色ID
             * Return      : none
             */
            loadCopyRoleRes ( roleId ) {
                let para = Object.assign ({}, {roleId: roleId})
                this.$store.dispatch ('loadSysRoleResAct', para).then (data => {
                    this.roleResTreeList = data
                    this.checkedKeys = Util.setTreeChecked(this.roleResTreeList,[])
                    this.expandedKeys = Util.expandedKeysAll(data,[])
                })
            },

            /**
             * Function    : handleChange
             * Description : 新增或删除角色用户
             * Input       : newTargetKeys direction moveKeys
             * Return      : none
             */
            handleChange ( newTargetKeys, direction, moveKeys ) {
                // 更新
                let userIds = moveKeys.join (',')
                let para = {roleId: this.roleId, userIds}
                let handleMethod
                if (direction === 'right') {
                    // 新增
                    handleMethod = 'addRoleUserAct'

                    if (!this.perms.addRoleUsers) {
                        this.$message.error ('不具备新增角色用户权限')
                        return
                    }
                } else {
                    // 刪除
                    handleMethod = 'delRoleUserAct'
                    if (!this.perms.delRoleUsers) {
                        this.$message.error ('不具备删除角色用户权限')
                        return
                    }
                }
                this.$store.dispatch (handleMethod, para).then (data => {
                    if (data.code === 0) {
                        // 成功
                        this.$message.success (data.message)
                        this.userKeys = newTargetKeys
                    } else {
                        this.$message.error (data.message)
                    }
                })
            }
        },
        created () {
            this.initQueryParms ()
            this.initPermission ()
            /**
             * 初始化的tab数据加载的处理
             */
            if (!this.perms.loadRoleResources && this.perms.findRoleUsers) {
                this.currentTabName = '2'
            }
            this.init ()
        }
    }
</script>
<style rel="stylesheet/less" lang="less">
    @import "~assets/nycss.less";
</style>
